package com.wqz.tacos.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wqz.tacos.data.OrderRepository;
import com.wqz.tacos.models.Order;
import com.wqz.tacos.models.Taco;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Repository
public class JdbcOrderRepository implements OrderRepository {
    private SimpleJdbcInsert orderInsert;
    private SimpleJdbcInsert orderTacoInsert;
    private ObjectMapper objectMapper;

    /**
     * 引入SimpleJdbcInsert来保持数据
     * @param jdbc
     */
    @Autowired
    public JdbcOrderRepository(JdbcTemplate jdbc) {
        this.orderInsert = new SimpleJdbcInsert(jdbc)
                .withTableName("Taco_Order")
                .usingGeneratedKeyColumns("id");
        this.orderTacoInsert = new SimpleJdbcInsert(jdbc)
                .withTableName("Taco_Order_Tacos");
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 保存必要的订单信息
     * @param order
     * @return
     */
    @Override
    public Order save(Order order) {
        order.setCreateTime(new Date());
        long orderId = saveOrderDetails(order);

        order.setId(orderId);

        List<Taco> tacos = order.getTacos();
        for (Taco taco : tacos) {
            saveTacoToOrder(taco, orderId);
        }
        return null;
    }

    /**
     *
     * @param taco
     * @param orderId
     */
    private void saveTacoToOrder(Taco taco, long orderId) {
        Map<String, Object> values = new HashMap<>();
        values.put("tacoOrder", orderId);
        values.put("taco", taco.getId());
        long id = orderTacoInsert.executeAndReturnKey(values)
                .longValue();
        log.info("保持到Taco_Order的数据中的订单id是%d", id);
    }

    /**
     * 将订单信息保存到数据库中并且返回order实例在数据库中的Id
     * @param order
     * @return
     */
    private long saveOrderDetails(Order order) {
        @SuppressWarnings("unchecked")
        Map<String, Object> values = objectMapper.convertValue(order, Map.class);
        values.put("creatTime", order.getCreateTime());

        long orderId = orderInsert.executeAndReturnKey(values)
                .longValue();
        log.info("order id is %d", orderId);
        return orderId;
    }
}
